using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WMS.Api.Application.Commands;
using WMS.Common;
using WMS.Common.Dtos;

namespace WMS.Api.Controllers
{
    /// <summary>
    /// 账户控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<AccountController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志</param>
        public AccountController(IMediator mediator, ILogger<AccountController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 用户登录（GET方式）
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="loginPwd">登录密码</param>
        /// <returns>登录结果</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ApiResult<UserLoginResponseDto>> UserLogin(string loginName, string loginPwd)
        {
            try
            {
                var command = new UserLoginCommand
                {
                    LoginName = loginName,
                    LoginPwd = loginPwd
                };
                
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户登录失败");
                return new ApiResult<UserLoginResponseDto>("登录失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 返回权限功能列表转成树形格式
        /// </summary>
        /// <param name="parentId">父Id</param>
        /// <returns>返回权限功能列表</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ApiResult<List<MenuItem>>> GetMenuItemList(int userId = 0)
        {
            try
            {
                var command = new GetMenuItemCommand
                {
                    UserId = userId
                };
                
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取菜单列表失败");
                return new ApiResult<List<MenuItem>>("获取菜单列表失败：" + ex.Message)
                {
                    code = StatusCodeEnum.ParamError,
                    isSuc = false
                };
            }
        }
    }
} 